<template>
    <div>
        <el-dialog
            v-model="dialogVisible"
            :title="editData?'编辑建筑':'新增建筑'"
            width="50%"
            @opened="handleDialogOpened"
            :before-close="handleClose"
            :close-on-click-modal="false"
            :close-on-press-escape="false"
        >
        <el-form
            ref="ruleFormRef"
            :model="ruleForm"
            :rules="rules"
            label-width="100px"
            status-icon
        >
            <el-form-item label="建筑名称" prop="name">
                <el-input v-model.trim="ruleForm.name" />
            </el-form-item>
            <el-form-item label="楼层数据" prop="floor">
                <div style="width: 100%;"><el-button style="float: right;" @click="handleAddFloor" size="small" type="primary" plain>新增</el-button></div>
                <el-table :data="floorTableData" style="width: 100%">
                    <el-table-column type="index" width="80" align="center" label="楼层" />
                    <el-table-column label="楼层别名">
                        <template #default="scope"> <el-input v-model="scope.row.name"></el-input></template>
                    </el-table-column>
                    <el-table-column label="地图">
                        <template #default="scope">
                            <el-select v-model="scope.row.mapId" placeholder="请选择">
                                <el-option
                                    v-for="item in mapOptions"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.id"
                                />
                            </el-select>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作">
                        <template #default="scope"><el-link @click="handleDeleteFloor(scope)" type="danger">删除</el-link></template>
                    </el-table-column>
                </el-table>
            </el-form-item>
            <el-form-item label="描述">
                <el-input v-model.trim="ruleForm.description" type="textarea" :rows="3" />
            </el-form-item>
        </el-form>

            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="handleClose">取 消</el-button>
                    <el-button type="primary" @click="handleConfirm(ruleFormRef)">确 认</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>
  
<script setup lang="ts">
import { ref, defineEmits, defineProps, watch, reactive, nextTick, onMounted, onUnmounted } from 'vue';
import type { FormInstance, FormRules } from 'element-plus'
import { addBuilding, updateBuilding } from '@/api/building';
import * as util from  '@/utils';
import { getMapList } from '@/api/map';

interface FloorData {
    name: string;
    mapId?: number | null;
}

const dialogVisible = ref(false);
const floorTableData = ref<Array<FloorData>>([]);
const mapOptions = ref<Array<any>>([]);

interface Props {
	visible: boolean;
    editData?: any;
}

interface RuleForm {
  name: string;
  floor?: any;
  description?: string;
}

const props = defineProps<Props>();
watch(()=>props.visible,val=>{ dialogVisible.value = val })

const emit = defineEmits<{
    'close': [value: any]
}>()

function handleClose(value){
    emit('close',value);
}

const ruleFormRef = ref<FormInstance>()
let ruleForm = reactive<RuleForm>({
    name: '',
    floor: null,
    description: ''
})

const validateFloor = (rule: any, value: any, callback: any) => {
  if (floorTableData.value.length > 0) {
    if(floorTableData.value.some(item=>!item.name || !item.mapId)){
        callback(new Error('请将楼层信息补充完整！'))
    }else {
        callback()
    }
  } else {
    callback()
  }
}

const rules = reactive<FormRules<RuleForm>>({
    name: [ { required: true, message: '请填写建筑名称', trigger: 'blur' }],
    floor: [ { validator: validateFloor } ]
})

function handleAddFloor(){
    floorTableData.value.push({
        name: '',
        mapId: null
    })
}

function handleDeleteFloor(scope){
    floorTableData.value.splice(scope.$index,1);
}

async function handleDialogOpened(){
    getMapList({ pageNo:1, pageSize: 999}).then(res=>{
        mapOptions.value = res.data.data;
    })
    for(let key in ruleForm){
        ruleForm[key] = props.editData?props.editData[key]: '';
    }
    floorTableData.value = [];
    if(props.editData?.floor){
        floorTableData.value = JSON.parse(props.editData.floor);
    }
    await nextTick();
    ruleFormRef.value.clearValidate();

}   

function handleConfirm(formEl: FormInstance){
    formEl.validate((valid, fields) => {
        if (valid) {
            const params = util.objectCopy(ruleForm);
            const editData = props.editData;
            if(!util.isEmpty(floorTableData.value)){
                params.floor = JSON.stringify(floorTableData.value);
            }
            if(editData){
                updateBuilding(editData.id,params).then(res=>{
                    handleClose('update');
                })
            }else{
                addBuilding(params).then(res=>{
                    handleClose('update');
                })
            }
        } else {
        console.log('error submit!', fields)
        }
    })
    
}

</script>

<style lang="scss" scoped>

</style>

